package com.csnf.dao;

import com.csnf.entity.Authors;
import com.csnf.entity.Books;
import com.csnf.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    //通过书籍名查询书籍和作者信息
    public List<Books> getBooksByName(String bookName) throws Exception {
        List<Books> booksList = new ArrayList<>();
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from books where book_name like concat('%',?,'%') ";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql, bookName);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            Books books = JdbcUtil.invokeObject(rs, Books.class);
            // 通过作者id查询作者信息
            String sql1 = "select * from authors where author_id=?";
            PreparedStatement ps1 = JdbcUtil.getPreparedStatement(conn, sql1, books.getAuthor_id());
            ResultSet rs1 = ps1.executeQuery();
            while(rs1.next()){
                Authors authors = JdbcUtil.invokeObject(rs1, Authors.class);
                books.setAuthors(authors);
            }
            booksList.add(books);
            JdbcUtil.close(rs1,ps1);
        }
        JdbcUtil.close(rs,ps,conn);
        return booksList;
    }

    public List<Books> getBooksByAuthor(Integer authorId) throws Exception {
        List<Books> booksList = new ArrayList<>();
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from books where author_id=?";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql, authorId);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            Books books = JdbcUtil.invokeObject(rs, Books.class);
            booksList.add(books);
        }
        JdbcUtil.close(rs,ps,conn);
        return booksList;
    }
}
